package com.hao.user.app.controller;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hao.common.code.ErrorCode;
import com.hao.common.execption.BusinessException;
import com.hao.common.response.BaseResponse;
import com.hao.common.utils.ResultUtils;
import com.hao.user.app.annotation.AuthCheck;
import com.hao.user.app.model.dto.user.*;
import com.hao.user.app.model.entity.Address;
import com.hao.user.app.model.entity.User;
import com.hao.user.app.model.vo.UserVO;
import com.hao.user.app.service.AddressService;
import com.hao.user.app.service.UserService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.TimeUnit;

import static com.hao.user.app.constant.RedisConstant.REDIS_PHONE_CODE;

/**
 * @author haoge
 * @version 1.0
 * @date 2023/5/21 9:24
 */
@Api (tags = "用户模块")
@RestController
@RequestMapping ("/user")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private JavaMailSender javaMailSender;

    @Resource
    private AddressService addressService;

    /**
     * 管理员添加用户
     *
     * @param userAddRequest
     * @return
     */
    @PostMapping ("/add")
    @AuthCheck (mustRole = "admin")
    public BaseResponse<Boolean> addUser(@RequestBody @Valid UserAddRequest userAddRequest) {
        if (userAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = userService.addUser(userAddRequest);
        return ResultUtils.success(result);
    }

    @GetMapping ("/isLogin")
    public Long isLogin() {
        try {
            User loginUser = userService.getLoginUser();
            return loginUser.getId();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 用户注册
     *
     * @param userRegisterRequest
     * @return
     */
    @PostMapping ("/register")
    public BaseResponse<Boolean> userRegister(@RequestBody @Valid UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = userService.userRegister(userRegisterRequest);
        return ResultUtils.success(result);
    }

    /**
     * 用户登录
     *
     * @param userLoginRequest
     * @param request
     * @return
     */
    @PostMapping ("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.userLogin(userLoginRequest, request);
        return ResultUtils.success(user);
    }

    /**
     * 用户退出登录
     *
     * @param request
     * @return
     */
    @PostMapping ("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 获取当前登录用户
     */
    @GetMapping ("/current")
    public BaseResponse<UserVO> getLoginUser(HttpServletRequest request) {
        User loginUser = userService.getLoginUser();
        UserVO userVO = new UserVO();
        if (loginUser != null) {
            try {
                BeanUtils.copyProperties(userVO, loginUser);
            } catch (IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        return ResultUtils.success(userVO);
    }

    @GetMapping ("/get")
    @AuthCheck (mustRole = "admin")
    public BaseResponse<UserVO> getUserById(Integer id) {

        if (id == null || id < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getById(id);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        }
        UserVO userVO = new UserVO();
        try {
            BeanUtils.copyProperties(userVO, user);
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        return ResultUtils.success(userVO);
    }

    /**
     * 更新用户
     */
    @PostMapping ("/update")
    @AuthCheck (anyRole = {"user", "admin"})
    public BaseResponse<Boolean> updateUser(@RequestBody @Valid UserUpdateRequest userUpdateRequest, HttpServletRequest request) {
        if (userUpdateRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = userService.updateUser(userUpdateRequest, request);
        return ResultUtils.success(result);
    }

    @PostMapping ("/delete")
    @AuthCheck (mustRole = "admin")
    public BaseResponse<Boolean> deleteUserById(Integer id) {
        if (id == null || id < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = userService.removeById(id);
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "删除失败");
        }
        return ResultUtils.success(result);
    }

    @GetMapping ("/list")
    @AuthCheck (mustRole = "admin")
    public BaseResponse<Page<UserVO>> listUserByPage(UserQueryRequest userQueryRequest) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Page<UserVO> userVOPage = userService.listUserByPage(userQueryRequest);
        return ResultUtils.success(userVOPage);
    }

    // TODO: 2023/5/21 待优化
    @PostMapping ("/sendMsg")
    public BaseResponse<String> sendMsg(@Valid @RequestBody PhoneRequest phoneRequest) {

        String code = RandomUtil.randomNumbers(6);
        log.info("短信验证码：" + code);
        redisTemplate.opsForValue().set(REDIS_PHONE_CODE + ":" + phoneRequest.getPhone(), code, 5L, TimeUnit.MINUTES);
        return ResultUtils.success("发送短信验证码成功");
    }

    @PostMapping ("/sendEmail")
    public BaseResponse<String> sendEmail(@RequestParam String email) {
        try {
            SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
            String code = RandomUtil.randomNumbers(6);

            redisTemplate.opsForValue().set(REDIS_PHONE_CODE + ":" + email, code, 5L, TimeUnit.MINUTES);

            simpleMailMessage.setSubject("验证码邮件");
            simpleMailMessage.setText("您收到的验证码是：" + code);
            simpleMailMessage.setFrom("1668173696@qq.com");
            simpleMailMessage.setTo("1668173696@qq.com");
            javaMailSender.send(simpleMailMessage);
            log.info("邮件验证码为" + code);
            return ResultUtils.success("发送邮件成功");
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "发送邮件失败");
        }
    }

    @PostMapping ("decrease")
    public boolean decreaseBalance(@RequestParam Long id, @RequestParam Double totalNum) {
        try {
            return userService.decreaseBalance(id, totalNum);
        } catch (Exception e) {
            return false;
        }
    }

    @GetMapping ("/address")
    public String getUserAddress(@RequestParam Long id){
        QueryWrapper<Address> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", id);
        queryWrapper.eq("status", 1);
        Address address = addressService.getOne(queryWrapper);

        return new StringBuilder().append(address.getProvince()).append(address.getCity()).append(address.getCounty()).append(address.getDetail()).toString();
    }
}
